
import 'package:flutter/material.dart';
import 'package:flutter_trip/dao/search_dao.dart';
import 'package:flutter_trip/models/search_model.dart';
import 'package:flutter_trip/pages/speak_page.dart';
import 'package:flutter_trip/widget/search_bar.dart';
import 'package:flutter_trip/widget/webview.dart';

const String URL ='https://m.ctrip.com/restapi/h5api/searchapp/search?source=mobileweb&action=autocomplete&contentType=json&keyword=长城';
const TYPES =[
  'channelgroup',
  'gs',
  'plane',
  'train',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup'
];
class SearchPage extends StatefulWidget {
  final bool hideLeft;
  final String searchUrl;
  final String keyword;
  final String hint;


  SearchPage(this.hideLeft, this.searchUrl, this.keyword, this.hint);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String resultString ='';
  late SearchModel searchModel;
  String keyword = '';

  @override
  void initState() {
    if(widget.keyword!=''){
      _onTextChange(widget.keyword);
    }
    // TODO: implement initState
    super.initState();

  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Column(
        children: [
          _appBar(),
         MediaQuery.removePadding(
           removeTop: true,
             context: context,
             child:  Expanded(
           flex: 1,
           child: ListView.builder(
               itemCount: _itemCount,
               itemBuilder: (BuildContext context, int index){
                 return _item(index);
               }),)),
          InkWell(
            onTap: (){
              String url ='https://m.ctrip.com/restapi/h5api/searchapp/search?source=mobileweb&action=autocomplete&contentType=json&keyword=';

            },
            child: Text('点击搜索接口'),
          ),
          Text(resultString),


        ],
      )
    );
  }
  int get _itemCount{
    if(resultString!=''){
      return searchModel.data.length;
    }else{
      return 0;
    }
  }
  _onTextChange(String text){
    print(text);
    keyword = text;
    if(keyword.length ==0){
        setState(() {
          resultString ='' ;
        });
        return;
    }
//    String url = widget.searchUrl+text;
    String url = URL+text;
    _handleRefresh(url,text);
  }
  _handleRefresh(url,text)async{
    SearchDao.fetch(url,text).then((SearchModel model){
      setState(() {
        resultString = '请求结果正确';
        searchModel = model;
        resultString = searchModel.data[0].url;

      });
    }).catchError((e){
      print(e.toString());
      setState(() {
        resultString = '';

      });

    });
    return null;
  }
  _appBar(){
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0x66000000),Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter
            )
          ),
          child:Container(
            padding: EdgeInsets.only(top: 20),
            height: 80,
            decoration: BoxDecoration(color: Colors.white),
            child: SearchBar(
                  (){
                    Navigator.pop(context);
                  },
                  (){},
                  (){
                       _jumpToSpeakPage();
                    },
                  (){},
              _onTextChange,
              defaultText: widget.keyword,
              hint: widget.hint,
              searchBarType: SearchBarType.normal,
              hideLeft: widget.hideLeft,
            ),
          ) ,
        )

      ],
    );

  }
  _jumpToSpeakPage(){
    Navigator.push(context, MaterialPageRoute(builder: (context)=>SpeakPage()));

  }
  _item(int index){
    SearchItem item = searchModel.data[index];
    return GestureDetector(
      onTap: (){
        Navigator.push(context, MaterialPageRoute(builder: (context)=>MyWebView(item.url, '000000', item.word, false)));
      },
      child:Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
          border: Border(bottom: BorderSide(width: 0.4,color: Colors.grey))
        ),
        child: Row(
          children: [
            Container(
              margin: EdgeInsets.all(1),
              child: Image(
                height: 26,
                width: 26,
                image: AssetImage(_typeImage(item.type)),
              ),
            ),
            Column(
              children: [
                Container(width: 300,child: _title(item),),
                Container(width: 300,
                  margin: EdgeInsets.only(top: 5),
                  child: _subTitle(item),),
              ],
            )
          ],
        ),
      ) ,
    );
  }
  _title(item){
    List<TextSpan> spans =[];
    spans.addAll(_keywordTextSpans(item.word,searchModel.keyword));
    spans.add(TextSpan(text: ' '+item.districtname,style: TextStyle(fontSize: 16,color: Colors.grey)),);
    return RichText(text: TextSpan(children: spans));
    return Text('${item.word} ${item.districtname}');
  }
  _subTitle(item){
    return Text('${item.word} ${item.districtname}');
  }
  _keywordTextSpans(String s,String k){
    List<TextSpan> spans =[];
    List<String> arr = s.split(k);
    TextStyle normalStyle = TextStyle(fontSize: 16,color: Colors.black87);
    TextStyle keywordlStyle = TextStyle(fontSize: 16,color: Colors.orange);
    for(int i=0;i<arr.length;i++){
      if((i+1)%2==0){
        spans.add(TextSpan(text: k,style: keywordlStyle));
      }
      String val = arr[i];
      if(val.length>0){
        spans.add(TextSpan(text: val,style: normalStyle));
      }
    }
    return spans;

  }
  _typeImage(String type){
      String path = 'travelgroup';
      for(final val in TYPES){

        if (type.contains(val)){
          path = val;
          break;
        }
      }
      return 'images/type_$path.png';
  }
}